package com.sgb.kjwl.view.ui.activity.pick;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.chuanglan.shanyan_sdk.listener.OneKeyLoginListener;
import com.chuanglan.shanyan_sdk.listener.OpenLoginAuthListener;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.databinding.ActivityPickCompanyListBinding;
import com.sgb.kjwl.di.pick.DaggerPickProjectComponent;
import com.sgb.kjwl.di.pick.PickProjectModule;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.view.event.ChooseAreaEvent;
import com.sgb.kjwl.view.event.special.QuickEntryEvent;
import com.sgb.kjwl.view.ui.quickentry.BackResultContentListener;
import com.sgb.kjwl.view.ui.quickentry.QuickEntryEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.model.entity.user.PickCompanyListEntity;
import com.sgb.kjwl.utils.ConfigUtils;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.pick.PickCompanyListAdapter;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.widget.MyItemDecoration;
import com.sgb.kjwl.view.widget.PickHallBidingPopWindow;
import com.sgb.kjwl.view.widget.pick.PickPopWindowView;
import com.sgb.kjwl.viewmodel.pick.PickCompanyListModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 招采企业
 */
public class PickCompanyListActivity extends AppActivity {
    private ActivityPickCompanyListBinding binding;
    @Inject
    PickCompanyListModel viewModel;

    private PickCompanyListAdapter pickCompanyListAdapter;
    private ThreeLevelAreaWindow mAddressPop;
    private PickHallBidingPopWindow pickTypePopWindow;
    private PickHallBidingPopWindow pickModelPopWindow;
    private boolean isChangeArea;
    private boolean isChangeType;
    private boolean isChangeModel;

    private List<PickSelectEntity> scaleDatas = new ArrayList<>();
    private List<PickSelectEntity> typeDates = new ArrayList<>();
    private List<PickSelectEntity> provinceDates = new ArrayList<>();
    private List<PickSelectEntity> cityDates = new ArrayList<>();

    //地区
    private List<String> citysNo = new ArrayList<>();
    //规模
    private List<String> scalesNo = new ArrayList<>();

    //搜索关键字
    private String searchName = "";
    private InputMethodManager im;

    //省
    private String areaCode;
    private String areaName;
    //地区
    private String cityNo;
    //类型
    private String typeNo;
    private String typeName;
    //规模
    private String modelNo;
    private String modelName;

    private Boolean isSearching = false;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPickProjectComponent.builder().appComponent(appComponent).pickProjectModule(new PickProjectModule(this)).build().inject(this);
    }

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, PickCompanyListActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(PickCompanyListActivity.this, R.layout.activity_pick_company_list);
        binding.setViewModel(viewModel);

        im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (null != im) {
            im.hideSoftInputFromWindow(binding.topLayout.etView.getWindowToken(), 0);
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void init() {
        binding.topLayout.ivBack.setOnClickListener(this);

        binding.topLayout.tvSearch.setOnClickListener(this);
        binding.topLayout.tvSearchDelete.setOnClickListener(this);
        binding.topLayout.etView.setHint("搜索企业名称");
        binding.imgBackTop.setOnClickListener(this);
        binding.tvType.setOnClickListener(this);
        binding.tvArea.setOnClickListener(this);
        binding.tvModel.setOnClickListener(this);
        binding.ivQuickEntry.setOnClickListener(this);

        binding.topLayout.etView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        binding.topLayout.etView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (isSearching) return true;
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (TextUtils.isEmpty(binding.topLayout.etView.getText().toString())) {
                        MToast.showToast(PickCompanyListActivity.this, "请输入搜索内容");
                        return true;
                    }
                    if (searchName.equals(binding.topLayout.etView.getText().toString())){
                        MToast.showToast(PickCompanyListActivity.this, "请输入不同的搜索内容");
                        return true;
                    }
                    isSearching = true;
                    searchName = binding.topLayout.etView.getText().toString();
                    if (!TextUtils.isEmpty(searchName)) {
                        viewModel.getData(searchName, modelNo, typeNo, cityNo, areaCode);
                    }
                }
                return false;
            }
        });

        if (pickCompanyListAdapter == null) {
            pickCompanyListAdapter = new PickCompanyListAdapter(getActivity(), null, new PickCompanyListAdapter.CallBack() {
                @Override
                public void onItemFocus(PickCompanyListEntity entity, int position) {
                    if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                        jumpLogin();
                    } else {
                        viewModel.userFocus(entity.getCompanyNo(), !entity.getFocus(), position);
                    }
                }
            });
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.shape_list_divide1));
        binding.recyclerView.addItemDecoration(divider);
        binding.recyclerView.setAdapter(pickCompanyListAdapter);
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initdata();
                binding.recyclerView.setLoadingMoreEnabled(true);
            }

            @Override
            public void onLoadMore() {
                if (pickCompanyListAdapter.getDatas().size() < viewModel.total) {
                    viewModel.getMoreData(searchName, modelNo, typeNo, cityNo, areaCode);
                } else {
                    binding.recyclerView.setLoadingMoreEnabled(false);
                }
            }
        });

        binding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                switch (newState){
                    /*正在拖拽*/
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        /*惯性滑动中*/
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        int position = manager.findLastVisibleItemPosition();
                        if (position > 10) {
                            binding.imgBackTop.setVisibility(View.VISIBLE);
                        } else {
                            binding.imgBackTop.setVisibility(View.GONE);
                        }
                        break;
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

            }
        });

        pickCompanyListAdapter.setOnItemClick(new AdapterOnItemClick<PickCompanyListEntity>() {
            @Override
            public void onItemClick(PickCompanyListEntity pickCompanyListEntity, int position) {
                if (TextUtils.isEmpty(String.valueOf(pickCompanyListEntity.getCompanyNo()))) {
                    ToastUtil.show(getActivity(), "企业店铺no不能为空");
                    return;
                }
                WebsiteInfoActivity.start(getActivity(), String.valueOf(pickCompanyListEntity.getCompanyNo()), WebsiteInfoActivity.WEBSITE_FOR_COMPANY);
            }
        });

        // 类型
        pickTypePopWindow = new PickHallBidingPopWindow(PickCompanyListActivity.this);
        pickTypePopWindow.setBgView(binding.grayLayout);
        pickTypePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                typeNo = ((PickSelectEntity) key1).getNo();
                typeName = ((PickSelectEntity) key1).getProjectscale();
                if (!"全部".equals(typeName)) {
                    isChangeType = true;
                    updateChooseTextStatus(binding.tvType,1,typeName);
                }else{
                    isChangeType = false;
                    updateChooseTextStatus(binding.tvType,0,"经营类型");
                }
                initdata();
            }
        });
        pickTypePopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (!isChangeType) {
                    updateChooseTextStatus(binding.tvType,0,"经营类型");
                } else {
                    updateChooseTextStatus(binding.tvType,1,typeName);
                }
            }
        });
        // 规模
        pickModelPopWindow = new PickHallBidingPopWindow(PickCompanyListActivity.this);
        pickModelPopWindow.setBgView(binding.grayLayout);
        pickModelPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                modelNo = ((PickSelectEntity) key1).getNo();
                modelName = ((PickSelectEntity) key1).getProjectscale();
                if(!"全部".equals(modelName)){
                    isChangeModel = true;
                    updateChooseTextStatus(binding.tvModel,1,modelName);
                }else{
                    isChangeModel = false;
                    updateChooseTextStatus(binding.tvModel,0,"招采规模");
                }
                initdata();
            }
        });
        pickModelPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (!isChangeModel) {
                    updateChooseTextStatus(binding.tvModel,0,"招采规模");
                } else {
                    updateChooseTextStatus(binding.tvModel,1,modelName);
                }
            }
        });
        initdata();
        viewModel.getSelecteScaleData();
        viewModel.getProvinceData();
        viewModel.getServiceTypeList();
        initAddressPopup();
    }

    private void initAddressPopup() {
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setBgView(binding.grayLayout);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                areaCode = entity.getProvinceNo();
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    areaName = entity.getProvinceName();
                    areaCode = entity.getProvinceNo();
                    cityNo = "";
                    if ("0".equals(areaCode)) {
                        areaName = "地区";
                    }
                    updateChooseTextStatus(binding.tvArea, 1, areaName);
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        cityNo = entity.getCityNo();
                        areaName = entity.getCityName();
                        viewModel.getAddressCityData(scrData, cityNo);
                        updateChooseTextStatus(binding.tvArea, 1, areaName);
                    }
                } else {
                    areaName = "地区";
                    areaCode = "";
                    cityNo = "";
                    updateChooseTextStatus(binding.tvArea, 0, areaName);
                }
                viewModel.getData(searchName, modelNo, typeNo, cityNo, areaCode);


            }
        });
        mAddressPop.setOnDismissListener(() -> {
            updateChooseTextStatus(binding.tvArea, "地区".equals(areaName) ? 0 : 1, areaName);
        });
    }

    public void initdata() {
        viewModel.getData(searchName, modelNo, typeNo, cityNo, areaCode);
        binding.topLayout.tvSearch.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.right_view:
//                showPopWindow();
                break;
            case R.id.tv_search:
                searchName = binding.topLayout.etView.getText().toString();
                if (!TextUtils.isEmpty(searchName)) {
                    viewModel.getData(searchName, modelNo, typeNo, cityNo, areaCode);
                }
                break;
            case R.id.tv_search_delete:
                binding.topLayout.etView.setText("");
                searchName = "";
                viewModel.getData(searchName, modelNo, typeNo, cityNo, areaCode);
                break;
            case R.id.img_back_top:
                binding.imgBackTop.setVisibility(View.GONE);
                binding.recyclerView.getLayoutManager().scrollToPosition(0);
                break;
            case R.id.tv_type:
                showTypePopWindow();
                break;
            case R.id.tv_model:
                showModelPopWindow();
                break;
            case R.id.tv_area:
                showProvincePopWindow();
                break;
            case R.id.iv_quick_entry:
                EventBus.getDefault().postSticky(new QuickEntryEvent(binding.ivQuickEntry, new BackResultContentListener() {
                    @Override
                    public boolean backResult(QuickEntryEntity entity) {
                        finish();
                        return false;
                    }
                }));
                break;
        }
    }

    /**
     * 省份
     */
    private void showProvincePopWindow() {
        if(TextUtils.isEmpty(areaName)){
            areaName = "地区";
        }
        updateChooseTextStatus(binding.tvArea, TextUtils.isEmpty(areaCode) && TextUtils.isEmpty(cityNo) ? -1 : -2, areaName);
        mAddressPop.showPopwindow0(binding.tvArea);
    }

    private void showTypePopWindow() {
        if(TextUtils.isEmpty(typeName)){
            typeName = "经营类型" ;
            pickTypePopWindow.setDefItem();
        }
        updateChooseTextStatus(binding.tvType, -1, typeName);
        pickTypePopWindow.showPopwindow0(binding.tvType);
        pickTypePopWindow.setData(typeDates,false);
    }

    private void showModelPopWindow() {
        if(TextUtils.isEmpty(modelName)){
            modelName = "招采规模" ;
            pickModelPopWindow.setDefItem();
        }
        updateChooseTextStatus(binding.tvModel, -1, modelName);
        pickModelPopWindow.showPopwindow0(binding.tvModel);
        pickModelPopWindow.setData(scaleDatas,false);
    }

    public void setProvinceDatas(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (data != null && data.size() > 0) {
            scrData = data;
            mAddressPop.setData(scrData, true);
        } else {
            viewModel.getAddressCityData(scrData, cityNo);
        }
    }

    public void setCityDatas(List<PickSelectEntity> data) {
        cityDates.clear();
        cityDates.addAll(data);
        mAddressPop.setData(scrData, false);
    }

    public void setTypeDatas(List<PickSelectEntity> datas) {
        typeDates.clear();
        datas.add(0,new PickSelectEntity("","全部"));
        typeDates.addAll(datas);
    }

    public void setScaleDatas(List<PickSelectEntity> datas) {
        scaleDatas.clear();
        datas.add(0,new PickSelectEntity("","全部"));
        scaleDatas.addAll(datas);
    }

    public void showData(List<PickCompanyListEntity> list) {
        binding.imgBackTop.setVisibility(View.GONE);
        isSearching = false;
        binding.recyclerView.refreshComplete();
        if (list == null || list.size() == 0) {
            binding.recyclerView.setVisibility(View.GONE);
            binding.emptyView.setVisibility(View.VISIBLE);
        } else {
            binding.recyclerView.setVisibility(View.VISIBLE);
            binding.emptyView.setVisibility(View.GONE);
            pickCompanyListAdapter.setDatas(list);
        }
    }

    public void showMoreData(List<PickCompanyListEntity> list) {
        binding.imgBackTop.setVisibility(View.VISIBLE);
        binding.recyclerView.loadMoreComplete();
        binding.emptyView.setVisibility(View.GONE);
        pickCompanyListAdapter.addDatas(list);
    }


    /**
     * 更新选项颜色
     */
    private void updateChooseTextStatus(PickPopWindowView pickPopWindowView, int value, String name) {
        if (!TextUtils.isEmpty(name)) {
            if (name.length() > 4) {
                name = name.substring(0, 4) + "...";
            }
        }
        if (value == -1 || value == -2) {
            binding.popLine.setVisibility(View.VISIBLE);
            pickPopWindowView.setChooseData(R.drawable.member_pop_blue_bg2, R.mipmap.ic_up_arrow_n, R.color.color_333333,true,name);
        }else if (value == 0) {
            binding.popLine.setVisibility(View.GONE);
            pickPopWindowView.setChooseData(R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333,false,name);
        } else {
            binding.popLine.setVisibility(View.GONE);
            pickPopWindowView.setChooseData(R.drawable.search_new_blue_bg_10, R.mipmap.icon_down_red, R.color.color_main,false,name);
        }
    }

    public void setIsGz(boolean isGz, int position) {
        pickCompanyListAdapter.getDatas().get(position).setFocus(isGz);
        pickCompanyListAdapter.notifyDataSetChanged();
    }

    public void jumpLogin() {
        boolean shanyan = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.ShanYan, false);
        if (shanyan) {
            //校验权限
            //申请动态权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //6.0以上运行时权限处理
                EsayPermissions.with(PickCompanyListActivity.this).constantRequest().permission(PERMISSIONS).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        openLoginPage();
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        openLoginPage();
                    }
                });

            } else {
                //有权限
                openLoginPage();
            }

        } else {
            VerificationCodeLoginActivity.start(PickCompanyListActivity.this, EventConstant.EVENT_PICK_COMPANY_LIST_JUMP);
        }
    }

    /**
     * 拉起授权页
     */
    private void openLoginPage() {
        //设置授权页样式
        OneKeyLoginManager.getInstance().setAuthThemeConfig(ConfigUtils.getCJSConfig(this));
        //开始拉取授权页
        DialogHelper.showProgressDialog(this, null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(true);
        OneKeyLoginManager.getInstance().openLoginAuth(false, new OpenLoginAuthListener() {
            @Override
            public void getOpenLoginAuthStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code != 1000) {
                    VerificationCodeLoginActivity.start(PickCompanyListActivity.this, EventConstant.EVENT_PICK_COMPANY_LIST_JUMP);
                }
            }
        }, new OneKeyLoginListener() {
            @Override
            public void getOneKeyLoginStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code == 1000) {
                    OneKeyLoginEntity oneKeyLoginEntity = GsonManager.getInstance().getGson().fromJson(result, OneKeyLoginEntity.class);
                    oneKeyLoginEntity.setPlateform("Android");
                    viewModel.oneKeyLogin(oneKeyLoginEntity);
                }
            }
        });
    }

    /**
     * 一键登录成功
     *
     * @param loginEntity
     * @param phoneNumber
     */
    public void loginSucceed(LoginEntity loginEntity, String phoneNumber) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageData(phoneNumber);
        loginEvent.setMessageTag(EventConstant.EVENT_PICK_COMPANY_LIST_JUMP);
        loginEvent.setObject(loginEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void getUserMsgSucceed(UserMsgEntity userMsgEntity) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageTag(EventConstant.EVENT_USER_MSG);
        loginEvent.setMessageData(userMsgEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ChooseAreaEvent event) {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
